package com.app.xinfadi.ui.home;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.app.xinfadi.R;
import com.app.xinfadi.base.BaseFragment;
import com.app.xinfadi.dao.HomeDao;
import com.app.xinfadi.dao_bean.CenterPurchasePlanListBean;
import com.app.xinfadi.dao_bean.bean.CenterPurchasePlanBean;
import com.app.xinfadi.dao_bean.bean.CountBean;
import com.app.xinfadi.dao_bean.bean.PurchasePlanBean;
import com.app.xinfadi.dao_bean.bean.refresh_bean.HomeRefreshBean;
import com.app.xinfadi.ui.purchase_plan.center_purchase_plan.CenterPurchasePlanDetailActrvity;
import com.app.xinfadi.ui.purchase_plan.view.CenterPurchasePlanListAdapter;
import com.app.xinfadi.util.LogUtil;
import com.app.xinfadi.util.SharedPreferencesUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Function:
 * <br/>
 * Create on:2016/1/19 16:41
 * <br/>
 * Author:WuTengFei
 */
public class HomeFragment extends BaseFragment {
    private static final String TAG = HomeFragment.class.getSimpleName();
    private View view;
    private PullToRefreshListView pullToRefreshListView;
    private CenterPurchasePlanListAdapter centerPurchasePlanListAdapter;
    private TextView newPurchasePriceTv;
    private View newPurchasePriceRelay;
    private TextView noRunPlanNumTv;
    private TextView haveRunPlanNumTv;
    private int currentPage = 1;
    /*计划数量布局*/
    private View countView;
    /*topb布局*/
    private View headerView;

    public static HomeFragment getInstance() {
        HomeFragment instance = new HomeFragment();
        Bundle args = new Bundle();
//      args.putString("status", status);
        instance.setArguments(args);
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.home_layout_fragment, null);
        initView();
        EventBus.getDefault().register(this);
        return view;
    }

    private void getCount() {
        HomeDao homeDao = new HomeDao();
        homeDao.getCount(new Response.Listener<CountBean>() {
            @Override
            public void onResponse(CountBean countBean) {
                if (countBean.success) {
                    if (noRunPlanNumTv != null) {
                        noRunPlanNumTv.setText(countBean.count + "");
                    }
                }
            }
        });
        homeDao.getCounted(new Response.Listener<CountBean>() {
                               @Override
                               public void onResponse(CountBean countBean) {
                                   if (countBean.success) {
                                       if (haveRunPlanNumTv != null)
                                           haveRunPlanNumTv.setText(countBean.count + "");

                                   }
                               }
                           }
        );
    }

    private void initView() {
        addHeaderView();
        initListView();
    }

    /**
     * 首页数据刷新
     *
     * @param homeRefreshBean
     */
    public void onEventMainThread(HomeRefreshBean homeRefreshBean) {
        if(homeRefreshBean.refresh){
            initListData();
        }
    }

    private void initListView() {
        pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.pullToRefreshListView);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.getRefreshableView().addHeaderView(headerView);
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(context, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                        | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                if (PullToRefreshBase.Mode.PULL_FROM_START == pullToRefreshListView.getCurrentMode()) {
                    initListData();
                    new GetDataTask().execute();
                } else if (PullToRefreshBase.Mode.PULL_FROM_END == pullToRefreshListView.getCurrentMode()) {
//                    LogUtil.e("pull_down", "down currentPage："+currentPage);
                    currentPage++;
                    getPlans();
                    new GetDataTask().execute();
                }
//                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            }
        });
        initListData();

        centerPurchasePlanListAdapter = new CenterPurchasePlanListAdapter(context);
        pullToRefreshListView.setAdapter(centerPurchasePlanListAdapter);
        pullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {


            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LogUtil.e(TAG, "position:" + position);
                if (SharedPreferencesUtil.getInstance().getUserRole().equals("0")) {
                    //排除头布局
                    if (position != 1) {
                        Intent intent = new Intent(context, CenterPurchasePlanDetailActrvity.class);
                        intent.putExtra("type", Integer.valueOf(SharedPreferencesUtil.getInstance().getUserRole()));
                        intent.putExtra("plan_id", centerPurchasePlanListAdapter.getData().get(position - 2).PLAN_ID);
                        intent.putExtra("status", centerPurchasePlanListAdapter.getData().get(position - 2).STATUS);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("data", centerPurchasePlanListAdapter.getData().get(position - 2));
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                } else if (SharedPreferencesUtil.getInstance().getUserRole().equals("1")) {
                    Intent intent = new Intent(context, CenterPurchasePlanDetailActrvity.class);
                    intent.putExtra("type", Integer.valueOf(SharedPreferencesUtil.getInstance().getUserRole()));
                    intent.putExtra("plan_id", centerPurchasePlanListAdapter.getData().get(position - 1).PLAN_ID);
                    intent.putExtra("status", centerPurchasePlanListAdapter.getData().get(position - 1).STATUS);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", centerPurchasePlanListAdapter.getData().get(position - 1));
                    intent.putExtras(bundle);
                    startActivity(intent);
                }

            }
        });
    }

    public void initListData() {
        if (SharedPreferencesUtil.getInstance().getUserRole().equals("0")) {
            countView.setVisibility(View.VISIBLE);
            getCount();
        } else {
            countView.setVisibility(View.GONE);
        }
        getPlans();
    }

    public void getPlans() {
//        String myPatientsRingMessage[] = {"黄瓜", "西红柿", "青椒", "土豆", "油", "白菜", "胡萝卜", "大豆", "海带", "香菜"};
//        List<PurchasePlanBean> purchasePlanBeanList = new ArrayList<PurchasePlanBean>();
//        // 已经选的 49
//        for (int i = 0; i < myPatientsRingMessage.length * 1; i++) {
//            PurchasePlanBean purchasePlanBean = new PurchasePlanBean();
//            purchasePlanBean.purchaseName = myPatientsRingMessage[i % 10];
//            purchasePlanBeanList.add(purchasePlanBean);
//        }
//        refreshAdapter(purchasePlanBeanList);

        HomeDao homeDao = new HomeDao();
        homeDao.getPlans(currentPage, new Response.Listener<CenterPurchasePlanListBean>() {
            @Override
            public void onResponse(CenterPurchasePlanListBean centerPurchasePlanListBean) {
                if (centerPurchasePlanListBean.plans != null && centerPurchasePlanListBean.plans.size() > 0) {
                    refreshAdapter(centerPurchasePlanListBean.plans);
                }
            }
        });
    }

    /*添加头布局*/
    private void addHeaderView() {
        headerView = LayoutInflater.from(context).inflate(R.layout.home_header_layout, null);
        countView = headerView.findViewById(R.id.countView);

        newPurchasePriceTv = (TextView) headerView.findViewById(R.id.newPurchasePriceTv);
        newPurchasePriceRelay = headerView.findViewById(R.id.newPurchasePriceRelay);
        newPurchasePriceRelay.setOnClickListener(this);
        noRunPlanNumTv = (TextView) headerView.findViewById(R.id.noRunPlanNumTv);
        haveRunPlanNumTv = (TextView) headerView.findViewById(R.id.haveRunPlanNumTv);
        headerView.setClickable(false);


    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.newPurchasePriceTv:
//                Intent newPurchasePriceIntent  = new Intent(context,NewPurchasePriceActivity.class);
//                startActivity(newPurchasePriceIntent);

                break;
            case R.id.newPurchasePriceRelay:
                Intent newPurchasePriceIntent = new Intent(context, NewPurchasePriceActivity.class);
                startActivity(newPurchasePriceIntent);
                break;
        }
    }

    private class GetDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            pullToRefreshListView.onRefreshComplete();
            super.onPostExecute(result);
        }
    }

    private void refreshAdapter(List<CenterPurchasePlanBean> purchasePlanBeanList) {
        if (currentPage == 1) {
            centerPurchasePlanListAdapter.getData().clear();
        }
        centerPurchasePlanListAdapter.getData().addAll(purchasePlanBeanList);
        centerPurchasePlanListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
